<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button type="primary" @click="setaddress = true">从题库中选择</a-button>
          <a-button type="primary">
            <router-link class="text-white" :to="{name: '课后作业'}">返回</router-link>
          </a-button>
        </a-button-group>
      </div>
      <el-dialog class="school-form" title="题目选择" width="510px" :visible.sync="setaddress">
        <div class="row">
          <div class="col school-itembank border">
            <div class="text-center">题库组</div>
            <el-input style="padding:15px;" size="mini" placeholder="搜索" v-model="value1"></el-input>
            <ul class="list-group">
              <li
                class="list-group-item d-flex justify-content-between align-items-center"
                v-for="(v,i) in getschoolitembankgroup.filter(v=>v.name.includes(value1))"
                @click="packegekeyid = v.ID"
                :key="`1addhomework${i}`"
                :class="packegekeyid == v.ID?'bg-light':''"
                style="border:0;"
              >
                {{v.name}}
                <span class="badge badge-pill">
                  <i class="el-icon-arrow-right"></i>
                </span>
              </li>
            </ul>
          </div>
          <div class="col school-itembank border" v-loading="loading">
            <div class="text-center">答题</div>
            <el-input style="padding:15px;" size="mini" placeholder="搜索" v-model="value2"></el-input>
            <button
              class="school-itembank-lg btn-light btn btn-block btn-sm"
              v-for="(vo,k) in getlist"
              :key="`2addhomework${k}`"
              :label="vo.ID"
              @click="listchange(vo)"
            >{{vo.name}}</button>
          </div>
        </div>
      </el-dialog>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="学员" prop="student">
            <el-cascader
              style="width:100%;"
              v-model="liststudent"
              :options="options"
              :props="props"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="答题">
            <a-empty v-show="itembank.length===0">
              <span slot="description">请从题库中选题</span>
              <a-button type="primary" @click="setaddress = true">从题库中选择</a-button>
            </a-empty>
            <el-tag
              v-for="(item, k) in itembank"
              :key="`2addhomework${k}`"
              @click="index = k"
              closable
              :type="index ===k?'info':'success'"
              @close="close(k)"
            >{{item.name}}</el-tag>
            <div v-show="itembank.length">
              <el-form
                :model="itembankfrom"
                :rules="itembankrules"
                ref="ruleForm"
                label-width="100px"
                size="mini"
              >
                <el-form-item label="名称" prop="name">
                  <el-input v-model="itembankfrom.name"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                  <el-select @change="blur" v-model="itembankfrom.type" placeholder="请选择">
                    <el-option label="单选" value="单选"></el-option>
                    <el-option label="多选" value="多选"></el-option>
                    <el-option label="填空" value="填空"></el-option>
                    <el-option label="解答" value="解答"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="内容" prop="text">
                  <div class="content" ref="editor" style="text-align:left; width: 375px;"></div>
                </el-form-item>
                <el-form-item label="选项">
                  <div v-if="itembankfrom.type == '解答'">
                    <!-- <el-input v-model="ruleForm.data.answer" placeholder="请输入内容"></el-input> -->
                  </div>
                  <div v-else>
                    <el-button
                      @click="answerpush(true)"
                      type="warning"
                      icon="el-icon-circle-plus-outline"
                      circle
                    ></el-button>
                    <el-button
                      @click="answerpush(false)"
                      type="danger"
                      icon="el-icon-delete"
                      circle
                    ></el-button>
                    <div v-if="itembankfrom.type == '单选' ">
                      <el-radio
                        v-model="itembankfrom.data.answer"
                        v-for="(v,i) in itembankfrom.data.单选"
                        :key="`${i}itembank1`"
                        :label="v"
                      >{{v}}</el-radio>
                    </div>
                    <div v-else-if="itembankfrom.type == '多选'">
                      <el-checkbox-group v-model="itembankfrom.data.answer">
                        <el-checkbox
                          v-for="(v,i) in itembankfrom.data.多选"
                          :key="`${i}itembank2`"
                          :label="v"
                        >{{v}}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                    <div v-else-if="itembankfrom.type == '填空'">
                      <div v-for="(v,i) in itembankfrom.data.填空" :key="`${i}itembank3`">
                        <el-input v-model="itembankfrom.data.answer[i]" placeholder="请输入内容"></el-input>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="答案">
                  <div v-if="itembankfrom.type == '填空'">{{itembankfrom.data.answer.join(' ')}}</div>
                  <div v-else-if="itembankfrom.type == '多选'">{{itembankfrom.data.answer.join(' ')}}</div>
                  <div v-else>{{itembankfrom.data.answer?itembankfrom.data.answer:""}}</div>
                </el-form-item>
                <el-form-item label="解析">
                  <el-input v-model="itembankfrom.analysis"></el-input>
                </el-form-item>
                <el-form-item label="知识点">
                  <el-tooltip class="item" effect="dark" content="用空格分开" placement="top">
                    <el-input v-model="itembankfrom.knowledgepoints"></el-input>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="标签">
                  <el-tooltip class="item" effect="dark" content="用空格分开" placement="top">
                    <el-input v-model="itembankfrom.tags"></el-input>
                  </el-tooltip>
                </el-form-item>
              </el-form>
            </div>
          </el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">发送</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import E from "wangeditor";
import { mapGetters } from "vuex";
import { uniq } from "underscore";
import {
  asynccreatschoolhomework,
  asyncgetschoolitembankbygroupid
} from "../../../../plugins/api.js";
import { updateoss } from "../../../utils.js";
import emoji from "../../../../plugins/emoji.json";
export default {
  name: "addhomework",
  data() {
    return {
      value1: "",
      value2: "",
      props: { multiple: true },
      editor: null,
      list: [],
      liststudent: [],
      packegekeyid: "",
      loading: false,
      setaddress: false,
      itembank: [],
      index: 0,
      itembankfrom: {
        name: "",
        type: "单选",
        text: "",
        username: "",
        knowledgepoints: "",
        data: {
          单选: [],
          多选: [],
          填空: [],
          解答: "",
          answer: []
        },
        tags: "",
        analysis: ""
      },
      itembankrules: {
        name: [
          { required: true, message: "请输入答题名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        text: [{ required: true, message: "请输入答题题内容", trigger: "blur" }]
      },
      ruleForm: {
        ID: null,
        title: "",
        schoolclazzs: "",
        student: [],
        itembank: []
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        text: [
          { required: true, message: "请添加内容", trigger: "blur" },
          { max: 3000, message: "内容过于大", trigger: "blur" }
        ],
        student: [{ required: true, message: "请添加学生", trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters([
      "getschoolstudent",
      "getschoolclazz",
      "getschoolhomework",
      "getschoolitembankgroup"
    ]),
    options() {
      const { getschoolstudent, getschoolclazz } = this;
      const data = getschoolclazz
        .filter(v => ["2", "3", "4"].includes(v.type))
        .map(v => {
          const student = v.schoolstudentschoolclazz
            .filter(vo => vo.schoolclazzid == v.ID && vo.type == "在读")
            .map(vo => vo.schoolstudentid);
          const children = getschoolstudent
            .filter(vo => student.includes(vo.ID))
            .map(vo => {
              return {
                label: vo.name,
                value: vo.ID
              };
            });
          return {
            label: v.name,
            value: v.ID,
            children
          };
        });
      return data;
    },
    getlist() {
      const { list, value2 } = this;
      if (value2) {
        return list.filter(v => {
          const { name, tags, knowledgepoints, analysis } = v;
          const x = Object.values({
            name,
            tags,
            knowledgepoints,
            analysis
          }).join();
          return x.includes(value2);
        });
      }
      return list;
    }
  },
  watch: {
    async packegekeyid(schoolitembankgroupid) {
      this.list = [];
      this.loading = true;
      this.list = await asyncgetschoolitembankbygroupid({
        schoolitembankgroupid
      });
      this.loading = false;
    },
    index(v) {
      this.itembankfrom.text = this.editor.txt.html();
      this.itembankfrom = this.itembank[v];
      this.editor.txt.html(this.itembankfrom.text);
    }
  },
  methods: {
    blur(v) {
      if (v === "单选" && v === "解析") {
        this.itembankfrom.data = {
          单选: [],
          多选: [],
          填空: [],
          解答: "",
          answer: ""
        };
      } else {
        this.itembankfrom.data = {
          单选: [],
          多选: [],
          填空: [],
          解答: "",
          answer: []
        };
      }
    },
    listchange(id) {
      if (this.itembank.length > 10) return;
      this.itembank.push(JSON.parse(JSON.stringify(id)));
      if (this.itembank.length == 1) {
        this.itembankfrom = this.itembank[0];
        if (!this.editor) {
          this.editor = new E(this.$refs.editor);
          this.editor.customConfig.zIndex = 100;
          this.editor.customConfig.pasteFilterStyle = false;
          this.editor.customConfig.pasteIgnoreImg = false;
          this.editor.customConfig.customUploadImg = async (files, insert) => {
            const str = await updateoss(files);
            insert(str);
          };
          this.editor.customConfig.uploadImgMaxLength = 1;
          window.acce = this.editor;
          this.editor.customConfig.pasteTextHandle = content => {
            const re1 = /<[^>]+>/g;
            const re2 = /<\s*script[^>]*>(.|[\r\n])*?<\s*\/script[^>]*>/gi;
            const re3 = /<\s*style[^>]*>(.|[\r\n])*?<\s*\/style[^>]*>/gi;
            let data = content.replace(re3, "");
            data = data.replace(re2, "");
            data = data.replace(re1, "");
            return data;
          };
          this.editor.customConfig.emotions = [
            {
              title: "默认",
              type: "image",
              content: emoji
            }
          ];
          this.editor.customConfig.menus = [
            "head",
            "underline",
            "list",
            "justify",
            "quote",
            "emoticon",
            "image",
            "undo"
          ];
          this.editor.create();
        }
        this.editor.txt.html(this.itembankfrom.text);
      }
    },
    async submitForm() {
      this.itembankfrom.text = this.editor.txt.html();
      let student = [];
      const schoolclazz = [];
      let schoolclazzs = "";
      for (let v of this.liststudent) {
        student.push(v[1]);
        if (v[0]) {
          schoolclazz.push(v[0]);
        }
      }
      student = uniq(student);
      schoolclazzs = uniq(schoolclazz).join(",");
      this.ruleForm.student = student;
      this.ruleForm.schoolclazzs = schoolclazzs;
      this.ruleForm.itembank = JSON.stringify(this.itembank);
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          try {
            await asynccreatschoolhomework(this.ruleForm);
            await this.$store.dispatch("actionschoolhomework");
            this.setaddress = false;
            this.$message.success(`布置成功`);
            this.$router.push({
              name: "课后作业"
            });
          } catch (err) {
            this.$message.error(`布置失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    answerpush(i) {
      const { data, type } = this.itembankfrom;
      const length = data[type].length;
      const str = "ABCDEFGHIGK";
      if (i) {
        if (length < 10) {
          if (type === "填空") {
            data[type].push("");
          } else {
            data[type].push(str.charAt(length));
          }
        }
      } else {
        if (length > 0) {
          data[type].pop();
          data.answer = [];
        }
      }
    },
    close(k) {
      this.itembank.splice(k, 1);
      const index = this.itembank.findIndex(v => v.ID == this.itembankfrom.ID);
      console.log(index)
      if (index == -1) {
        this.index = 0;
      this.itembankfrom = this.itembank[this.index];
      this.editor.txt.html(this.itembankfrom.text);
      } else {
        this.index = index;
      }
    }
  },
  async beforeDestroy() {
    await this.$store.dispatch("actionschoolstudent");
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
.school-itembank {
  height: 400px;
  overflow-y: auto;
  padding-left: 0px;
  padding-right: 0px;
}
.school-itembank-lg {
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
  margin: 0;
}
</style>